﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.Menu;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.PersistenceObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.Menu.Interface;
using WMS.FC.Domain.Service.System;

namespace WMS.FC.Domain.Service.Menu
{
    public class GetMenuListService : ServiceBase, IGetMenuListService
    {
        protected readonly IMenuRepository menuRepository;

        public GetMenuListService(ILogger<ServiceBase> logger, IOptions<WmsSettings> options, IMapper mapper, IMenuRepository menuRepository) : base(logger, options, mapper)
        {
            this.menuRepository = menuRepository;
        }

        public async Task<ActionResult<List<MenuDO>>> GetMenuList(UserInfo userInfo)
        {
            var result = new ActionResult<List<MenuDO>>("获取菜单列表");
            try
            {
                var menuList = await menuRepository.GetMenuList();
                result.Data = GetMenuList(null, menuList);

            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }

        private List<MenuDO> GetMenuList(long? parentId, IEnumerable<MenuPO> menuPOList)
        {
            var menuList = menuPOList.Where(menuPO => menuPO.ParentId == parentId).OrderBy(menuPO => menuPO.SortNumber).Select(menuPO => mapper.Map<MenuDO>(menuPO)).ToList();
            foreach (var menu in menuList)
            {
                menu.Children = GetMenuList(menu.Id, menuPOList);
            }

            return menuList;
        }
    }
}
